#pragma once
#include <iostream>
#include <string>
#include <pthread.h>
namespace xyl
{
    class Thread
    {
    public:
        typedef enum
        {
            CREATED = 0,
            RUNNING,
            EXITED
        } ThreadStatus;
        typedef void *(*thread_func)(void *);
    public:
        Thread(int num, thread_func func, void *args)
            : _tid(0),
              _status(CREATED),
              _func(func),
              _args(args)
        {
            char name[64];
            snprintf(name, sizeof(name), "Thread_%d", num);
            _name = name;
        }
        int status() { return _status; }
        std::string name() { return _name; }
        pthread_t id() { return _status == RUNNING ? _tid : -1; }
        void run()
        {
            if (0 != pthread_create(&_tid, nullptr, _func, _args))
                exit(-1);
            _status = RUNNING;
        }
        void join()
        {
            if (0 != pthread_join(_tid, nullptr))
            {
                std::cerr << "main thread join thread " << _name << " error" << std::endl;
                exit(-2);
            }
            _status = EXITED;
        }
    private:
        pthread_t _tid;
        thread_func _func; // 线程函数
        std::string _name;
        void *_args;          // 传给线程的参数
        ThreadStatus _status; // 线程的状态
    };
}